﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using System.Web.Http;
using WebApi_SY.Entity;
using WebApi_SY.Models;

namespace WebApi_SY.Controllers
{
    // 锻打工步报工
    public class sli_mesrep_forgingController : ApiController
    {
        [System.Web.Http.HttpPost]
        public async Task<object> Insert([Microsoft.AspNetCore.Mvc.FromBody] sli_mesrep_forging[] options)
        {
            if (options == null || options.Length == 0)
            {
                return new { code = 400, msg = "无效请求", data = "输入数据为空" };
            }

            var context = new YourDbContext();
            try
            {
                foreach (var option in options)
                {
                    // 检查option是否为null
                    if (option == null) continue;

                    var header = new sli_mesrep_forging
                    {
                        // 直接赋值即可，类属性已支持null
                        Fwoid = option.Fwoid,
                        Fworkorder = option.Fworkorder,
                        Fmaterialid = option.Fmaterialid,
                        Fname = option.Fname,
                        Fdescription = option.Fdescription,
                        Fproductno = option.Fproductno,
                        Fslimatel = option.Fslimatel,
                        Fsliweightforging = option.Fsliweightforging,
                        Fheight = option.Fheight,
                        Fsliouterdiameter = option.Fsliouterdiameter,
                        Fsliinnerdiameter = option.Fsliinnerdiameter,
                        Fslihight = option.Fslihight,
                        Fstarttime = option.Fstarttime,
                        Fendtime = option.Fendtime,
                        Fstatrtemperature = option.Fstatrtemperature,
                        Fendtemperature = option.Fendtemperature,
                        Frolling = option.Frolling,
                        Fcheckerselft = option.Fcheckerselft,
                        Fchecker = option.Fchecker,
                        Fnote = option.Fnote,
                        Fchecked = option.Fchecked,
                        Fdate = option.Fdate
                    };
                    context.sli_mesrep_forging.Add(header);
                }

                // 处理全为null的情况
                if (!context.ChangeTracker.HasChanges())
                {
                    return new { code = 400, msg = "无效数据", data = "所有记录均为空对象" };
                }

                await context.SaveChangesAsync();
                return new { code = 200, msg = "Success", data = $"{options.Length} 条记录保存成功" };
            }
            catch (Exception ex)
            {
                // 记录完整错误信息（生产环境应使用日志）
                return new { code = 500, msg = "保存失败", data = ex.Message };
            }
        }

        [System.Web.Http.HttpPost]
        public async Task<object> Update([Microsoft.AspNetCore.Mvc.FromBody] sli_mesrep_forging option)
        {
            var context = new YourDbContext();
            try
            {
                var entity = await context.sli_mesrep_forging.FindAsync(option.Id);
                if (entity == null)
                    return new { code = 404, msg = "记录不存在", data = option.Id };

                entity.Fwoid = option.Fwoid;
                entity.Fworkorder = option.Fworkorder;
                entity.Fmaterialid = option.Fmaterialid;
                entity.Fname = option.Fname;
                entity.Fdescription = option.Fdescription;
                entity.Fproductno = option.Fproductno;
                entity.Fslimatel = option.Fslimatel;
                entity.Fsliweightforging = option.Fsliweightforging;
                entity.Fheight = option.Fheight;
                entity.Fstarttime = option.Fstarttime;
                entity.Fendtime = option.Fendtime;
                entity.Fstatrtemperature = option.Fstatrtemperature;
                entity.Fendtemperature = option.Fendtemperature;
                entity.Frolling = option.Frolling;
                entity.Fcheckerselft = option.Fcheckerselft;
                entity.Fchecker = option.Fchecker;
                entity.Fnote = option.Fnote;
                entity.Fchecked = option.Fchecked;
                entity.Fdate = option.Fdate;

                await context.SaveChangesAsync();
                return new { code = 200, msg = "修改成功", data = option.Id };
            }
            catch (Exception ex)
            {
                return new { code = 500, msg = "失败", data = ex.ToString() };
            }
        }

        [System.Web.Http.HttpPost]
        public async Task<object> Delete(List<int> ids)
        {
            var context = new YourDbContext();
            try
            {
                foreach (var id in ids)
                {
                    var entity = await context.sli_mesrep_forging.FindAsync(id);
                    if (entity != null)
                        context.sli_mesrep_forging.Remove(entity);
                }
                await context.SaveChangesAsync();
                return new { code = 200, msg = "删除成功", data = ids };
            }
            catch (Exception ex)
            {
                return new { code = 500, msg = "失败", data = ex.ToString() };
            }
        }

        [System.Web.Http.HttpGet]
        public IHttpActionResult GetPaged(
            int page = 1,
            int pageSize = 10,
            string Fworkorder = null,
            string Fproductno = null)
        {
            var context = new YourDbContext();
            IQueryable<sli_mesrep_forging> query = context.sli_mesrep_forging;

            if (!string.IsNullOrEmpty(Fworkorder))
                query = query.Where(q => q.Fworkorder == Fworkorder);

            if (!string.IsNullOrEmpty(Fproductno))
                query = query.Where(q => q.Fproductno == Fproductno);

            var totalCount = query.Count();
            var totalPages = (int)Math.Ceiling((double)totalCount / pageSize);
            var data = query.OrderByDescending(x => x.Id)
                            .Skip((page - 1) * pageSize)
                            .Take(pageSize)
                            .ToList();

            return Json(new
            {
                code = 200,
                msg = "OK",
                data = new
                {
                    totalCount,
                    totalPages,
                    currentPage = page,
                    pageSize,
                    data
                }
            });
        }
    }

    // 轧打工步报工（结构与锻造完全相同）
    public class sli_mesrep_rollingController : ApiController
    {
        [System.Web.Http.HttpPost]
        public async Task<object> Insert([Microsoft.AspNetCore.Mvc.FromBody] sli_mesrep_rolling[] options)
        {
            // 检查输入是否为空
            if (options == null || options.Length == 0)
            {
                return new { code = 400, msg = "无效请求", data = "输入数据为空" };
            }

            var context = new YourDbContext();
            try
            {
                int validCount = 0;

                foreach (var option in options)
                {
                    // 跳过数组中的空元素
                    if (option == null) continue;

                    var header = new sli_mesrep_rolling
                    {
                        // 直接赋值，所有属性都支持 null
                        Fwoid = option.Fwoid,
                        Fworkorder = option.Fworkorder,
                        Fmaterialid = option.Fmaterialid,
                        Fname = option.Fname,
                        Fdescription = option.Fdescription,
                        Fproductno = option.Fproductno,
                        Fslimatel = option.Fslimatel,
                        Fsliweightforging = option.Fsliweightforging,
                        Fheight = option.Fheight,
                        Fsliouterdiameter = option.Fsliouterdiameter,
                        Fsliinnerdiameter = option.Fsliinnerdiameter,
                        Fslihight = option.Fslihight,
                        Fstarttime = option.Fstarttime,
                        Fendtime = option.Fendtime,
                        Fstatrtemperature = option.Fstatrtemperature,
                        Fendtemperature = option.Fendtemperature,
                        Frolling = option.Frolling,
                        Fcheckerselft = option.Fcheckerselft,
                        Fchecker = option.Fchecker,
                        Fnote = option.Fnote,
                        Fchecked = option.Fchecked,
                        Fdate = option.Fdate,
                        Fshrinkage = option.Fshrinkage
                    };

                    context.sli_mesrep_rolling.Add(header);
                    validCount++;
                }

                // 检查是否有有效记录
                if (validCount == 0)
                {
                    return new { code = 400, msg = "无效数据", data = "所有记录均为空对象" };
                }

                await context.SaveChangesAsync();
                return new { code = 200, msg = "Success", data = $"{validCount} 条记录保存成功" };
            }
            catch (Exception ex)
            {
                // 生产环境应记录完整日志，但只返回简要信息
                return new
                {
                    code = 500,
                    msg = "保存失败",
                    data = $"错误: {ex.Message}" // 避免返回完整堆栈
                };
            }
        }

        [System.Web.Http.HttpPost]
        public async Task<object> Update([Microsoft.AspNetCore.Mvc.FromBody] sli_mesrep_rolling option)
        {
            var context = new YourDbContext();
            try
            {
                var entity = await context.sli_mesrep_rolling.FindAsync(option.Id);
                if (entity == null)
                    return new { code = 404, msg = "记录不存在", data = option.Id };

                entity.Fwoid = option.Fwoid;
                entity.Fworkorder = option.Fworkorder;
                entity.Fmaterialid = option.Fmaterialid;
                entity.Fname = option.Fname;
                entity.Fdescription = option.Fdescription;
                entity.Fproductno = option.Fproductno;
                entity.Fslimatel = option.Fslimatel;
                entity.Fsliweightforging = option.Fsliweightforging;
                entity.Fheight = option.Fheight;
                entity.Fstarttime = option.Fstarttime;
                entity.Fendtime = option.Fendtime;
                entity.Fstatrtemperature = option.Fstatrtemperature;
                entity.Fendtemperature = option.Fendtemperature;
                entity.Frolling = option.Frolling;
                entity.Fcheckerselft = option.Fcheckerselft;
                entity.Fchecker = option.Fchecker;
                entity.Fnote = option.Fnote;
                entity.Fchecked = option.Fchecked;
                entity.Fdate = option.Fdate;
                entity.Fcheckerselft = option.Fcheckerselft;
                entity.Fshrinkage = option.Fshrinkage;

                await context.SaveChangesAsync();
                return new { code = 200, msg = "修改成功", data = option.Id };
            }
            catch (Exception ex)
            {
                return new { code = 500, msg = "失败", data = ex.ToString() };
            }
        }

        [System.Web.Http.HttpPost]
        public async Task<object> Delete(List<int> ids)
        {
            var context = new YourDbContext();
            try
            {
                foreach (var id in ids)
                {
                    var entity = await context.sli_mesrep_rolling.FindAsync(id);
                    if (entity != null)
                        context.sli_mesrep_rolling.Remove(entity);
                }
                await context.SaveChangesAsync();
                return new { code = 200, msg = "删除成功", data = ids };
            }
            catch (Exception ex)
            {
                return new { code = 500, msg = "失败", data = ex.ToString() };
            }
        }

        [System.Web.Http.HttpGet]
        public IHttpActionResult GetPaged(
            int page = 1,
            int pageSize = 10,
            string Fworkorder = null,
            string Fproductno = null)
        {
            var context = new YourDbContext();
            IQueryable<sli_mesrep_rolling> query = context.sli_mesrep_rolling;

            if (!string.IsNullOrEmpty(Fworkorder))
                query = query.Where(q => q.Fworkorder == Fworkorder);

            if (!string.IsNullOrEmpty(Fproductno))
                query = query.Where(q => q.Fproductno == Fproductno);

            var totalCount = query.Count();
            var totalPages = (int)Math.Ceiling((double)totalCount / pageSize);
            var data = query.OrderByDescending(x => x.Id)
                            .Skip((page - 1) * pageSize)
                            .Take(pageSize)
                            .ToList();

            return Json(new
            {
                code = 200,
                msg = "OK",
                data = new
                {
                    totalCount,
                    totalPages,
                    currentPage = page,
                    pageSize,
                    data
                }
            });
        }
    }
}